package com.cn.zpark.servlet;

import com.cn.zpark.beans.User;
import com.cn.zpark.utils.DruidUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.cn.zpark.servlet
 * @ClassName: FindUserAllServlet
 * @Description:
 * @author: RZS
 * @date: 2022/4/21  10:35
 */
@WebServlet("/findUserAll.do")
public class FindUserAllServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 准备连接数据库信息
        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet res = null;

        // 准备一个list集合存放user对象
        List<User> list = new ArrayList<>();

        try {
            // 获取连接
            conn = DruidUtils.getConn();
            // 编写sql
            String sql = "select id, uname, pwd from tab1";
            // 创建预编译sql对象
            stat = conn.prepareStatement(sql);
            // 替换占位符
            // 执行sql，并且拿到返回结果集
            res = stat.executeQuery();
            // 循环取出数据存放到list集合中
            while (res.next()) {
                // 创建user对象
                User user = new User();
                user.setId(res.getInt("id"));
                user.setUname(res.getString("uname"));
                user.setPwd(res.getString("pwd"));

                // 添加user对象到集合
                list.add(user);
                System.out.println(user);
            }
            // 绑定数据到请求域
            request.setAttribute("users", list);
            // 转发给JSP处理
            request.getRequestDispatcher("jsp/demo01.jsp").forward(request, response);
            /**
             * RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/demo01.jsp");
             * dispatcher.forward(request, response);
             */

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            DruidUtils.close(res, stat, conn);
        }

    }
}
